<template>
  <div class="login">
    <div class="login-con">
      <!-- 顶部切换 -->
      <ul class="menu-tab">
        <li v-for="item in menuData" :key="item.txt" :class="{ current: item.current }" @click="clickMenu(item)">
          {{ item.txt }}
        </li>
      </ul>

      <el-card style="width: 400px;margin: 50px auto;">
        <!-- 表单开始 -->
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
          <el-form-item prop="username">
            <label>手机号</label>
            <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="password">
            <label>密码</label>
            <el-input v-model="ruleForm.password" type="password" autocomplete="off" minlength="6" maxlength="15" />
          </el-form-item>
          <el-form-item prop="passwords" v-show="model === 'register'">
            <label>重复密码</label>
            <el-input v-model="ruleForm.passwords" minlength="6" maxlength="15" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button :disabled="btn" type="primary" class="login-btn block" @click="submitForm(ruleFormRef)">{{ model
                === "login" ? "登录" : "注册"
            }}</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表单结束 -->





    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import link from "../api/request"
import { el } from "element-plus/es/locale";
import { useRouter, useRoute } from "vue-router"
import axios from "axios";
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import { useStore } from 'vuex';
import { getUserInfo, updateUserPass } from '../api/api';
import { click } from "dom7";

const route = useRoute();


let router = useRouter()
const store = useStore();
const model = ref("login");

//表单
const ruleForm = reactive({
  username: "",
  password: "",
  passwords: "",
});

const ruleFormRef = ref<FormInstance>();



const menuData = reactive([
  { txt: "登录", current: true, type: "login" },
  { txt: "注册", current: false, type: "register" },
]);

//切换模块 通过添加class来改变选中转态
const clickMenu = (data: any) => {
  //将所有的状态都变为 false
  menuData.forEach((item) => {
    item.current = false;
  });

  //选中的那个为ture
  data.current = true;
  model.value = data.type;
};



//表单验证*****************************************

//用户名 - 手机号
var checkUser = (rule: any, value: any, callback: any) => {
  let reg = /^1(3|4|5|7|8)\d{9}$/;
  if (!value) {
    return callback(new Error("手机号不能为空"));
  }

  else if (!reg.test(value)) {
    return callback(new Error('手机号不正确'))
  } else {
    callback();
  }


};


//密码
const validatePass = (rule: any, value: any, callback: any) => {

  let reg = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,15}$/;// 验证密码 6至15位的字母+数字 

  if (value === "") {
    callback(new Error("密码不能为空"));
  } else if (!reg.test(value)) {
    return callback(new Error('密码必须6-15字母+数字'))
  } else {
    callback();
  }
};


//重复密码 - 登录无需重复密码
const validatePass2 = (rule: any, value: any, callback: any) => {
  //判断是登录还是注册,登录无需重复校验
  if (model.value === "login") {
    callback();
  }

  //注册校验
  if (value === "") {
    callback(new Error("重复密码不能为空！"));
  } else if (value !== ruleForm.password) {
    callback(new Error("两次密码必须相同！"));
  } else {
    callback();
  }
};


//按钮是否可按
let btn = ref(false)

watch(ruleForm, (newval, oldval) => {

  //登录
  if (model.value === 'login') {
    if (newval.username != '' && newval.password != '') {
      btn.value = false
    } else {
      btn.value = true
    }
  }

  //注册
  else {
    if (newval.username != '' && newval.password != '' && newval.passwords != '') {
      btn.value = false
    } else {
      btn.value = true
    }

  }

})



//校验准侧
const rules = reactive({
  // 校验器  validator  trigger - 校验方式:失去焦点
  username: [{ validator: checkUser, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
  passwords: [{ validator: validatePass2, trigger: 'blur' }]
})


//表单提交**********************************
// FormInstance 饿了么接口 规范每一项属性
const submitForm = (formEl: FormInstance | undefined) => {

  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (model.value === 'login') {
        let data = {
          phone: ruleForm.username,
          password: ruleForm.password
        }
        // console.log(111);

        link("/users/api/login", "POST", data).then(async (ok: any) => {
          if (ok.data.errorCode === 0) {
            ElMessage("登录成功");

            //保存token
            store.commit("updateToken", ok.data.data.token)
            // console.log(store.state._token)
            // 保存 userId
            store.commit("updateUserId", ok.data.data.userId)

            //保存用户名
            //  store.commit("updateUserId", ok.data.data.userId)
            let res: any = await getUserInfo(store.state.userId)

            // console.log(res.data.data.info.userName)

            store.commit("updateName", res.data.data.info.userName)
            console.log(store.state.Name)



            if (route.query.refer) {
              router.push({
                path: route.query.refer as string
              })
            } else {
              router.push("/account")
            }

          } else if (ok.data.errorCode === 3) {
            ElMessage.error("用户名或密码错误");
            return
          } else if (ok.data.errorCode === 2) {
            ElMessage.error("该手机号未注册");
            return
          } else if (ok.data.errorCode === 1) {
            ElMessage.error("数据不能为空");
            return
          } else {
            ElMessage.error("登录失败,请检查用户名或者密码是否输入正确");
          }

          console.log(ok.data.errorCode);

        })
      } else {
        let data = {
          phone: ruleForm.username,
          password: ruleForm.password
        }


        link("/users/api/register", "POST", data).then((ok: any) => {
          if (ok.data.errorCode === 0) {
            ElMessage('注册成功')
            model.value = 'login'
            menuData.forEach(v => {
              v.current = false
            })
            menuData[0].current = true
          } else if (ok.data.errorCode === 3) {
            ElMessage.error('用户名被占用')
          } else if (ok.data.errorCode === 1) {
            ElMessage.error('数据不能为空')
          } else if (ok.data.errorCode === 2) {
            ElMessage.error('缺失参数')
          } else {
            ElMessage.error('未知错误')
          }

          console.log(ok);

        })


      }
    } else {

      return false
    }
  });
};


const resetForm = (formEL: FormInstance | undefined) => {
  if (!formEL) return
  formEL.resetFields()
}





</script>

<style lang="scss">
.login {
  background: url('https://img.36krcdn.com/20220627/v2_32d6baa246924e8699019d4282d304d7_img_jpg') no-repeat center center/cover;
  height: 100%;
}

html,
body,
#app {
  height: 100%;
}

.menu-tab {
  text-align: center;

  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #333;
    border-radius: 2px;
    cursor: pointer;
  }

  .current {
    background-color: rgba(255, 255, 255, 0.5);
  }
}

.demo-ruleForm {
  width: 320px;
  margin: 20px auto;

  label {
    display: block;
    margin-bottom: 3px;
    font-size: 14px;
    color: #333;
  }

  .block {
    display: block;
    width: 100%;
  }

  .login-btn {
    margin-top: 20px;
  }
}

.menu-tab .current {
  background-color: #409eff;
  border-radius: 6px;
  color: #fff;
}
</style>